package com.zrh.jsd.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(tags = "类用途描述：fileDownLoad测试", value = "据说不显示,并且是真的")
@Component
@RestController
@RequestMapping("/fileDownLoad")
public class FileDownLoadController {
    /**
     * 以流的方式下载
     *
     * @param
     * @param response 响应内容
     */
    @ApiOperation("方法用途描述：fileDownLoad")
    @GetMapping("")
    public void download(HttpServletResponse response) {
        // path是指欲下载的文件的路径
        File file = new File("D:/a/agency.json");

        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
             OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        ) {
            // 取得文件名
            String filename = file.getName();
            // 获取下载文件的输入流
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            // 清空response
            response.reset();
            // 重新设置response
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            // 写入下载文件的输出流
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            //TODO 记录日志并做相关业务
        }
    }
}
